#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const net = require('net');

console.log('[启动助手] 开始启动融媒智创工坊开发环境...');

// 检查端口是否被占用
function checkPort(port) {
  return new Promise((resolve) => {
    const server = net.createServer();
    server.listen(port, () => {
      server.once('close', () => resolve(true));
      server.close();
    });
    server.on('error', () => resolve(false));
  });
}

// 查找可用端口
async function findAvailablePort(startPort = 5679) {
  for (let port = startPort; port < startPort + 10; port++) {
    if (await checkPort(port)) {
      return port;
    }
  }
  throw new Error('无法找到可用端口');
}

// 启动进程并监控
function startProcess(command, args, options = {}) {
  return new Promise((resolve, reject) => {
    console.log(`[启动助手] 执行: ${command} ${args.join(' ')}`);
    
    const child = spawn(command, args, {
      stdio: 'inherit',
      shell: true,
      ...options
    });

    child.on('error', reject);
    child.on('exit', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(new Error(`进程退出，代码: ${code}`));
      }
    });

    return child;
  });
}

// 延迟函数
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function main() {
  try {
    // 清理可能存在的端口占用
    console.log('[启动助手] 检查端口占用情况...');
    
    // 预编译预加载脚本和主进程
    console.log('[启动助手] 编译预加载脚本和主进程...');
    await startProcess('npm', ['run', 'build:preload']);
    await startProcess('npm', ['run', 'build:main']);
    
    console.log('[启动助手] 编译完成，启动开发服务器...');
    
    // 使用concurrently启动开发环境
    const devProcess = spawn('npm', ['run', 'dev'], {
      stdio: 'inherit',
      shell: true
    });

    // 监听进程退出
    devProcess.on('exit', (code) => {
      console.log(`[启动助手] 开发服务器退出，代码: ${code}`);
      process.exit(code);
    });

    devProcess.on('error', (error) => {
      console.error('[启动助手] 启动失败:', error);
      process.exit(1);
    });

    // 捕获Ctrl+C退出信号
    process.on('SIGINT', () => {
      console.log('\n[启动助手] 收到退出信号，正在关闭服务器...');
      devProcess.kill('SIGINT');
      setTimeout(() => {
        process.exit(0);
      }, 1000);
    });

    console.log('[启动助手] 开发环境已启动，按 Ctrl+C 退出');

  } catch (error) {
    console.error('[启动助手] 启动失败:', error.message);
    process.exit(1);
  }
}

// 检查Node.js版本
const nodeVersion = process.version;
const requiredVersion = '16.0.0';
if (nodeVersion < `v${requiredVersion}`) {
  console.error(`[启动助手] 需要 Node.js >= ${requiredVersion}，当前版本: ${nodeVersion}`);
  process.exit(1);
}

main().catch(console.error);